package com.naojump.android.twicca.picasa;

import static com.naojump.util.NUtils.lconv;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.naojump.android.gdata.client.NClientLogin;
import com.naojump.android.picasa.NPicasaWebAlbums;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.xml.parsers.DocumentBuilderFactory;

/**
 * NUploadActivity
 * 
 * @author Naoto Murata
 * @since 2
 * @version 8
 */
public class NUploadActivity extends Activity {

    /**
     * NUploadThread
     * 
     * @author Naoto Murata
     * @since 2
     * @version 8
     */
    @SuppressWarnings("synthetic-access")
    private class NUploadThread extends Thread {

        /** Tag */
        private final String TAG = NUploadThread.class.getName();

        /**
         * @see java.lang.Thread#run()
         */
        @Override
        public void run() {
            if (DEBUG)
                Log.d(TAG, "run");

            Intent intent = getIntent();
            Bundle extras = intent.getExtras();

            if (extras.getBoolean("background") == true) {
                mHandler.sendEmptyMessage(HttpStatus.SC_OK);
            }

            NClientLogin.Status status = (NClientLogin.Status) extras
                    .get("status");
            String userId = extras.getString("userId");
            mLh2 = new NPicasaWebAlbums(userId, status);
            String albumId = extras.getString("albumId");
            long size = extras.getLong("size");
            String title = extras.getString("title");

            int code = 0;
            try {
                HttpResponse res = mLh2.postMedia(albumId, intent,
                        getContentResolver().openInputStream(intent.getData()),
                        size, title);
                code = res.getStatusLine().getStatusCode();

                switch (code) {
                case HttpStatus.SC_OK:
                case HttpStatus.SC_CREATED:
                    Document doc = DocumentBuilderFactory.newInstance()
                            .newDocumentBuilder().parse(
                                    res.getEntity().getContent());

                    // content : direct link to the image
                    // alternate : page link to picasa web albums
                    // canonical : page link to picasa web albums (short)
                    for (Node entry : lconv(doc.getElementsByTagName("entry"))) {
                        for (Node child : lconv(entry.getChildNodes())) {
                            if ("content".equals(child.getNodeName())) {
                                intent.putExtra("content", child
                                        .getAttributes().getNamedItem("src")
                                        .getNodeValue());
                            } else if ("link".equals(child.getNodeName())) {
                                NamedNodeMap attrs = child.getAttributes();
                                if ("alternate".equals(attrs
                                        .getNamedItem("rel").getNodeValue())) {
                                    intent.putExtra("alternate", attrs
                                            .getNamedItem("href")
                                            .getNodeValue());
                                } else if ("http://schemas.google.com/photos/2007#canonical"
                                        .equals(attrs.getNamedItem("rel")
                                                .getNodeValue())) {
                                    intent.putExtra("canonical", attrs
                                            .getNamedItem("href")
                                            .getNodeValue());
                                }
                            }
                        }
                    }
                    break;
                }

            } catch (Exception e) {
                intent.putExtra("exception", e);
            }

            if (extras.getBoolean("background") == false) {
                intent.putExtra("code", code);
                mHandler.sendEmptyMessage(code);
            }
        }

    }

    /** DEBUG */
    private static final boolean DEBUG = false;

    /** Tag */
    private static final String TAG = NUploadActivity.class.getName();

    /** Picasa Web Albums handler */
    private NPicasaWebAlbums mLh2;

    /** Executor service */
    private ExecutorService mExec;

    /** Uploaded notification handler */
    private Handler mHandler;

    /** Uploading dialog */
    private ProgressDialog mDlg;

    /**
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @SuppressWarnings( { "synthetic-access", "unchecked" })
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (DEBUG)
            Log.d(TAG, "onCreate");

        String albumTitle = getIntent().getExtras().getString("albumTitle");
        String msg = getString(R.string.uploading) + "\n\nTo: " + albumTitle;

        mDlg = new ProgressDialog(this);
        mDlg.setTitle(R.string.app_name);
        mDlg.setMessage(msg);
        mDlg.setButton(DialogInterface.BUTTON_POSITIVE,
                getString(R.string.abort),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mLh2.abortPost();
                        mExec.shutdownNow();
                        dialog.dismiss();
                        finish();
                    }
                });
        mDlg.show();

        if (getLastNonConfigurationInstance() == null) {
            mExec = Executors.newSingleThreadExecutor();
            mHandler = new Handler() {

                @Override
                public void handleMessage(Message msg) {
                    mDlg.dismiss();
                    mExec.shutdown();
                    setResult(msg.what, getIntent());
                    finish();
                }
            };
            mExec.submit(new NUploadThread());
        } else {
            Map<String, Object> b = (Map<String, Object>) getLastNonConfigurationInstance();
            mExec = (ExecutorService) b.get("mExec");
            mHandler = (Handler) b.get("mHandler");
        }
    }

    /**
     * @see android.app.Activity#onRetainNonConfigurationInstance()
     */
    @Override
    public Object onRetainNonConfigurationInstance() {
        if (DEBUG)
            Log.d(TAG, "onRetainNonConfigurationInstance");

        Map<String, Object> b = new HashMap<String, Object>();
        b.put("mExec", mExec);
        b.put("mHandler", mHandler);
        return b;
    }

}
